<template lang="pug">
el-dialog(
  :visible.sync="show"
  width="900px"
  top="5vh"
  @open="beforeOpen"
  :before-close="handleClose"
  custom-class="dialog-border"
  :close-on-click-modal="false"
)
  .modal-title(slot="title") 编辑材料SKU表
  .modal-content
    .sample-name 材料名称：{{detail.name}}
    .spec-sku-table-body
      navbar(:navbar="detail.spec.prices.header" isHandle)
      .table-list
        .table-tr(v-for="row, rowIndex in detail.spec.prices.body" :key="`input_${rowIndex}`" v-if="rowIndex === 0")
          .table-td(
            v-for="item, index in row"
            :key="index"
          )
            .table-td-body.table-td-input(v-if="index > (row.length - 6)")
              el-input(size="mini" placeholder="0.00" v-if="index === (row.length - 5)" @change="changePrice(5, 'min_selling_price')" v-model="skuForm.min_selling_price")
              el-input(size="mini" placeholder="0.00" v-if="index === (row.length - 4)" @change="changePrice(4, 'max_selling_price')" v-model="skuForm.max_selling_price")
              el-input(size="mini" placeholder="0.00" v-if="index === (row.length - 3)" @change="changePrice(3, 'shop_price')" v-model="skuForm.shop_price")
              el-select(size="mini" placeholder="请选择" v-if="index === (row.length - 2)" @change="changePrice(2, 'unit')" v-model="skuForm.unit")
                el-option(v-for="item, index in unitList" :key="index" :label="item.label" :value="item.value")
              el-input(size="mini" type="number" placeholder="0" v-if="index === (row.length - 1)" @change="changePrice(1, 'store_count')" v-model="skuForm.store_count")
            .table-td-body(v-else)
          //- .table-td.table-td-del
        .table-tr(v-for="row, rowIndex in detail.spec.prices.body" :key="rowIndex")
          .table-td(
            v-for="item,index in row"
            :key="index"
          )
            .table-td-body.table-td-input(v-if="index > (row.length - 6)")
              el-input(size="mini" v-model="row[index]" placeholder="请输入价格" @change="changeCostPrice(item, index, row)" v-if="index === (row.length - 5)")
              el-input(size="mini" v-model="row[index]" placeholder="请输入价格" @change="changeCostPrice(item, index, row)" v-else-if="index === (row.length - 4)")
              el-input(size="mini" v-model="row[index]" placeholder="请输入价格" @change="changeCostPrice(item, index, row)" v-else-if="index === (row.length - 3)")
              el-select(size="mini" v-model="row[index]" placeholder="请选择" v-else-if="index === (row.length - 2)")
                el-option(v-for="item, index in unitList" :key="index" :label="item.label" :value="item.value")
              el-input(size="mini" placeholder="请输入库存" v-model="row[index]" @change="changeCostPrice(item, index, row)" type="number" v-else)
            .table-td-body(v-else) {{item}}
  .modal-footer(slot="footer")
    el-button(size="small" @click="handleClose") 取消
    el-button(size="small" name="primary" @click="save") 确定
</template>

<script>
import { getMaterialDetail, saveOrUpdate } from 'api'
import navbar from '@/components/navbar'
export default {
  name: 'changeStockModal',
  props: {
    show: Boolean,
    item: Object
  },
  components: {
    navbar
  },
  data () {
    return {
      skuForm: {
        min_selling_price: '',
        max_selling_price: '',
        shop_price: '',
        unit: '',
        store_count: ''
      },
      unitList: [
        { label: 'm²', value: 'm²' },
        { label: 'm', value: 'm' },
        { label: '件', value: '件' },
        { label: '套', value: '套' },
        { label: '块', value: '块' },
        { label: '个', value: '个' },
      ],
      detail: {
        spec: {
          prices: {
            header: [],
            body: []
          }
        }
      }
    }
  },
  methods: {
    beforeOpen () {
      this.getDetail()
    },
    async save () {
      try {
        let num = 0
        let countStatus = 0
        let storeCount = 0
        let reg = /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/
        let reg1 = /^[+]{0,1}(\d+)$/
        // let specFilter = this.detail.spec.items.every(item => {
        //   let isChildName = item.values.every(row => !!row.name)
        //   return item.name && item.values.length && isChildName
        // })
        // if (!specFilter) {
        //   this.$message.error('请仔细检查材料规格是否有未填写的字段！')
        //   return
        // }
        this.detail.spec.prices.body.forEach((item, index) => {
          let len = item.length
          if (reg.test(parseFloat(item[len - 5])) && reg.test(parseFloat(item[len - 4])) && reg.test(parseFloat(item[len - 3]))) num++
          if (parseInt(item[len - 1]) && reg.test(item[len - 1])) storeCount++
          if (reg1.test(item[len - 1])) countStatus++
        })
        if (num !== this.detail.spec.prices.body.length) {
          this.$message.error('请输入正确的SKU价格！')
          return
        }
        if (countStatus !== this.detail.spec.prices.body.length) {
          this.$message.error('请仔细检查您设置的库存是否为正整数！')
          return
        }
        if (!storeCount) {
          this.$message.error('SKU中至少有一项规格必须有库存！')
          return
        }
        this.submitLoading = this.$loading({
          lock: true,
          text: '数据提交中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.detail.type = 1
        await this.$axios.post(saveOrUpdate, { content: { ...this.detail } })
        this.submitLoading.close()
        this.$message.success('修改成功！')
        this.$emit('save')
      } catch (err) {
        this.submitLoading.close()
        this.locking = false
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    // 批量改变规格价格
    changePrice (index, key) {
      let reg = /^\d+(\.\d+)?$/
      if (index === 5 && !reg.test(this.skuForm.min_selling_price)) {
        this.$message.error('请输入正确的价格！')
        return
      }
      if (index === 4 && !reg.test(this.skuForm.max_selling_price)) {
        this.$message.error('请输入正确的价格！')
        return
      }
      if (index === 3 && !reg.test(this.skuForm.shop_price)) {
        this.$message.error('请输入正确的价格！')
        return
      }
      this.detail.spec.prices.body.forEach(row => {
        this.setSkuTable(row, index, key)
      })
    },
    setSkuTable (row, num, key) {
      this.$set(row, row.length - num, this.skuForm[key] ? this.skuForm[key] : row[row.length - num])
    },
    // 单个修改规格价格
    changeCostPrice (val, index, row) {
      let reg = /^\d+(\.\d+)?$/
      if (!reg.test(val)) {
        this.$message.error('请输入正确的数字！')
        this.vaild = true
      } else {
        this.vaild = false
      }
    },
    async getDetail () {
      try {
        console.log(this.item)
        const { ResultSet } = await this.$axios.post(getMaterialDetail, { content: { materialId: this.item.materialId } })
        let newForm = { ...ResultSet.userData.Material, ...ResultSet.userData, country: ResultSet.userData.Material.country + '' }
        let newSpec = {
          items: ResultSet.userData.items,
          prices: ResultSet.userData.table
        }
        newForm.spec = newSpec
        this.detail = newForm
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    handleClose () {
      this.$emit('close')
    }
  },
}
</script>

<style lang="scss" scoped>
.table-list {
  & .table-tr {
    display: flex;
    & .table-td {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 44px;
      min-width: 100px;
      flex: 1;
      border: 1px solid #DDD;
      border-top: none;
      border-right: none;
      &:last-child {
        border-right: 1px solid #DDD;
      }
      & .table-td-body {
        text-align: center;
        &.table-td-input {
          width: 100px;
        }
      }
    }
  }
}
.sample-name {
  margin-bottom: 5px;
  font-size: 14px;
}
</style>